package juc.topic;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 三个线程交替打印出a1Ab2Bc3C.....z26Z
 */
public class AlternatePrintingNumberLetter03 {
    private static final ReentrantLock lock = new ReentrantLock();

    private static final Condition numCondition = lock.newCondition();
    private static final Condition letterLowCondition = lock.newCondition();
    private static final Condition letterUpCondition = lock.newCondition();

    //0表示小写字母线程执行，1表示数字线程执行 2表示大写字母线程执行
    private static int flag = 0;


    public static void main(String[] args) {
            start();
    }

    public static void start(){
        new Thread(() -> {
            for (int i = 1; i <= 26; i++) {
                lock.lock();
                try {
                    while (flag != 1) {
                        numCondition.await();
                    }
                    System.out.print(i);
                    flag = 2;//该执行大写字母线程
                    //唤醒letterCondition
                    letterUpCondition.signal();//唤醒大写字母线程
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }
        }, "数字线程").start();



        new Thread(() -> {
            for (char i = 'a'; i <= 'z'; i++) {
                lock.lock();
                try {
                    while (flag != 0) {
                        try {
                            letterLowCondition.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print(i);
                    flag = 1; //该执行数字线程
                    numCondition.signal();//唤醒数字线程
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally{
                    lock.unlock();
                }
            }
        }, "小写字母线程").start();






        new Thread(() -> {
            for (char i = 'A'; i <= 'Z'; i++) {
                lock.lock();
                try {
                    while (flag != 2) {
                        try {
                            letterUpCondition.await();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    System.out.print(i);
                    flag = 0;//该执行小写字母线程
                    letterLowCondition.signal();//唤醒小写字母线程
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally{
                    lock.unlock();
                }
            }
        }, "大写字母线程").start();
    }
}
